package com.integrationpath.mengine.util;

import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.web.ServletCacheAdministrator;

import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;

public class OSCacheAdmin {
    
    /**
     * flush the CacheFilter according to dependent group
     *
     * @param request the HttpServletRequest of the user
     * @param groupNames a string collection of group names
     */
    public static void flushCacheGroup(HttpServletRequest request, Collection groupNames) {
    	Cache cache = ServletCacheAdministrator.getInstance(request.getSession().getServletContext()).getCache(request, PageContext.APPLICATION_SCOPE); 
        Iterator groups = groupNames.iterator();
        while (groups.hasNext()) {
            String group = (String) groups.next();
            cache.flushGroup(group);
        }
    }
    
    public static void flushCache(HttpServletRequest request) {
    	Cache cache = ServletCacheAdministrator.getInstance(request.getSession().getServletContext()).getCache(request, PageContext.APPLICATION_SCOPE); 
            cache.flushAll(new Date());
    }
    
    public static void flushCacheKey(HttpServletRequest request, String key) {
    	Cache cache = ServletCacheAdministrator.getInstance(request.getSession().getServletContext()).getCache(request, PageContext.APPLICATION_SCOPE); 
            cache.flushEntry(key);
    }    
    
    @SuppressWarnings("deprecation")
	public static void flushCachePattern(HttpServletRequest request, String pattern) {
    	Cache cache = ServletCacheAdministrator.getInstance(request.getSession().getServletContext()).getCache(request, PageContext.APPLICATION_SCOPE); 
            cache.flushPattern(pattern);
    }   
}
